/***
 * @Author:xxx
 * @Date:2020-11-01 19:32:37
 * @LastModifiedBy:xxx
 * @Last Modified time:2020-11-01 19:32:37
 */


import React, {Fragment, useEffect, useRef ,useState} from 'react';
import {useDrop,useDrag} from 'react-dnd';
import {Modal} from 'antd';
import  ItemTypes  from '../daoDemo2/ItemTypes';
import {DaoEchartsShow} from './daoEchartsShow';
import '../daoDemo2/index.css';
import EditCurveForm from '../../Modal/edit-curve-form ';
import {useSelector,useDispatch} from 'react-redux';   // 代替connect
import {delectCurveInDao2,getSelectedCurves2,getEditCurveInfo2,isUpdatePages,returnInit2} from '../../../redux/actions';





let count = 0;



export const Curve = (props)  => {   // 接收传入的属性 
  const {curve,dao_id } = props;
  const {curve_name,type,curve_id,title,left_data,right_data,color,width,xData,id,curve_unit,line_type} = curve;
  //console.log("curves",props,curve,dao_id,moveCurve,index,curve_name,type,curve_id,title,left_data,right_data,color,width,xData);
  const ref = useRef(null)

  const [, drop] = useDrop({   // 可接受放置的对象    
    accept: ItemTypes.CURVE,
    hover () {
      if (!ref.current) {
        return   
      }
      // const dragIndex = item.index
      // const hoverIndex = index

      // // Don't replace items with themselves
      // if (dragIndex === hoverIndex) { 
      //   return
      // }

      // // Determine rectangle on screen
      // const hoverBoundingRect = ref.current?.getBoundingClientRect()

      // // Get vertical middle
      // const hoverMiddleY =
      //   (hoverBoundingRect.right - hoverBoundingRect.left) / 2

      // // Determine mouse position
      // const clientOffset = monitor.getClientOffset()

      // // Get pixels to the top
      // const hoverClientY = clientOffset.x - hoverBoundingRect.left

      // // Only perform the move when the mouse has crossed half of the items height
      // // When dragging downwards, only move when the cursor is below 50%
      // // When dragging upwards, only move when the cursor is above 50%

      // // Dragging downwards
      // if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
      //   return
      // }

      // // Dragging upwards
      // if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
      //   return
      // }

      // // Time to actually perform the action
      // moveCurve(dragIndex, hoverIndex)
      // // Note: we're mutating the monitor item here!
      // // Generally it's better to avoid mutations,
      // // but it's good here for the sake of performance
      // // to avoid expensive index searches. 
      // item.index = hoverIndex
    },
  })

  const [{isDragging}, drag] = useDrag({   // 拖拽 对象
    item: { curve_name,type,curve_id,title,left_data,right_data,color,width,xData,id ,curve_unit,line_type},  //index, 
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const daosDataList = useSelector(state => state.daosDataList2);   // 从state中取 数据
  const updatePages = useSelector(state => state.updatePages); 
  const cancelSelected = useSelector(state => state.cancelSelected); 
  const dispatch = useDispatch()   // 像state 更改 数据
    

  useEffect(()=>{
    if(isDragging){    // 实时删除移动后的曲线
      daosDataList.forEach((item1) => {
        if(item1.id === dao_id){
          item1.curves.forEach((item,index) => {
            if(item.curve_name === curve_name){
              // 删除该曲线,并更新状态
              item1.curves.splice(index,1)
              dispatch(delectCurveInDao2(daosDataList)); 
            }
          })
        }
      })
    }
  },[isDragging])
  

  const [isSelectCurve, setIsSelectCurve] = useState(false);
  // const [_draggable, set_draggable] = useState(false);   // 是否可以人工绘制
  const [visible, setVisible] = useState(false);
  const [formRef, setFormRef] = useState('');
  const [color1, setColor1] = useState(curve.color);

  const editCurveInfo = () => {   // 曲线属性设置完毕;   有文件时，才可以修改曲线属性，不然没有id，无法找到修改的曲线
    //console.log("curve",curve);
    const id = curve.id;    // curve_id
    const curve_name = formRef.current.getFieldValue('curve_name');
    const title = formRef.current.getFieldValue('curve_name_another');
    const left_data = formRef.current.getFieldValue('curve_left');
    const width = formRef.current.getFieldValue('curve_width');
    const right_data = formRef.current.getFieldValue('curve_right');
    const line_type=formRef.current.getFieldValue('line_type');
    const curve_unit=formRef.current.getFieldValue('curve_unit');
    const color = color1;
    const data = {  
      id: id,
      curve_name: curve_name,
      title: title,
      left_data: Number(left_data),
      right_data: Number(right_data),
      width: width,
      color: color,
      line_type:line_type,
      curve_unit:curve_unit
    }
    console.log("获取曲线属性",data)
    dispatch(getEditCurveInfo2(data));   // 在redux中修改曲线属性     
    dispatch(isUpdatePages(!updatePages));
    setVisible(false);
  }

  const handleCancel = () => {
    //setFormRef('');  // 清空数据
    setVisible(false);
  }

  // function onClickByIcon(e,info) {   // 是否可以人工绘制
  //   e.stopPropagation();   // 阻止冒泡：不影响 父div 的点击事件
  //   set_draggable(!_draggable);
  //   const data = {
  //     curve_id: info.curveId,
  //     title: info.curve_title
  //   };
  //   dispatch(updateDraggable(data));   // 切换reducer中的状态
  // }

  // function onClickReset(e,info) {   // 是否可以重置 绘制过的曲线
  //   e.stopPropagation();   // 阻止冒泡：不影响 父div 的点击事件
  //   var newCurves,xdata;
  //   if(docData.doc_type === "纯数据文件"){
  //     newCurves = docData.curves;
  //   }else if(docData.doc_type === "绘图文件"){
  //     newCurves = docData.docData.curves;
  //   }
  //   newCurves.map((item) => {
  //     if(item.curve_id === info.curveId){
  //       xdata = item.xData;
  //     }
  //   })
  //   const data = {
  //     curve_id: info.curveId,
  //     xdata: xdata
  //   }
  //   dispatch(dragCurveData(data));   // 重置曲线的xdata
  //   dispatch(isUpdatePages(!updatePages));
  // }

  const onClick = (info) => {  // 实现 曲线框 的单击和双击事件    
    count += 1;
    setTimeout(() => {
      if(count === 1){
        const curve_id = info.curveId;
        const title = info.curve_title;
        const type = info.type;
        const xData = info.xData;
        dispatch(getSelectedCurves2({curve_id,title,type,xData})); 
        setIsSelectCurve(!isSelectCurve);
      }else if(count === 2){
        setVisible(true);
      }
      count = 0;
    },300)  
  };

  // useEffect(()=>{    // 这里为了设置 同时选中，有问题！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
  //   isSelectAll = {curve_id,isSelectCurve};
  //   //console.log("is111",id,isSelectCurve,isSelectAll);
  //   //CurveShow(id,title,curveShow.data);
  // },[isSelectCurve]);

  useEffect(() => {
    console.log("接收",cancelSelected);
    setIsSelectCurve(false);
    dispatch(returnInit2([]));   // 清空选中的曲线
  },[cancelSelected])


  drag(drop(ref))   // 既可以拖拽，也可以放置
  return (
    <Fragment>
      <div 
        ref={ref} 
        className={isSelectCurve ? "curve-title-select" :"curve-title"} 
        onClick={() => onClick({daoId:dao_id,curveId:curve_id,curve_title:title, xData: xData, type:type})} 
        style={{
          color: color
        }}
        >
          <div className="left-data">{left_data}</div>
          {title} ({curve_unit})&nbsp;&nbsp;&nbsp;
          {/* {isSelectCurve ? <i 
                              id="iconId"
                              className= "iconfont penicon" 
                              style={_draggable ? {color: color} : {color: 'gray'}}
                              onClick={(e) => onClickByIcon(e,{curveId:curve_id,curve_title:title})}                             
                            >
                              &#xe742;
                            </i> : null
          } 
           {isSelectCurve ? <i 
                              id="iconId"
                              className= "iconfont penicon" 
                              style={{color: 'gray'}}
                              onClick={(e) => onClickReset(e,{curveId:curve_id,curve_title:title})}                             
                            >
                              &#xe73a;
                            </i> : null} */}
          <div className="right-data">{right_data}</div>
          <div style={{ borderBottomStyle: "solid",borderBottomColor:color, borderBottomWidth:width, marginBottom: 2}}></div>
      </div> 

      <Modal
        title="曲线属性"
        visible={visible === true}
        onOk={editCurveInfo}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        destroyOnClose={true}
      >
        <EditCurveForm 
          curve = {curve}
          setForm = {(formRef) => {setFormRef(formRef)}}
          setColor = {(color) => {setColor1(color)}}
        />
      </Modal>
    </Fragment>    
  )
};


// 曲线的 数据显示

export const CurveShow = ({ curve,isDraggable }) => {   // 接收传入的属性
  const depthDataa = useSelector(state => state.depthDataa2);
  const chartZoom = useSelector(state => state.gridConfig.chartZoom);
  const isSelect = false;
 return ( 
   <div 
    className={isSelect ?"curve-show-select" : "curve-show"} 
    style={{height: ((depthDataa[depthDataa.length-1] - depthDataa[0])/5)*2*chartZoom  }}
  >
     <DaoEchartsShow curve={curve} isDraggable={isDraggable}/>
   </div>  
 )
};